/**
 * @file 照片配置
 * @author 李刚
 * @date 2021-09-25 15:24:11
 */

layui.define(['element', 'layer','upload', 'form', 'zmnSelect', 'zmnOmsSelect', '$http','previewer'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let $http = layui.$http;
    let layer = layui.layer;
    let zmnSelect = layui.zmnSelect;
    let zmnOmsSelect = layui.zmnOmsSelect;
    let upload = layui.upload;
    let CONF_BASE_URL = '/conf/attachment/orderPicture';
    var previewer = layui.previewer;
    let timestamp = new Date().getTime();

    /**
     * 判断是否是正整数
     * @param val {number/string} 字符串或数字
     * @returns {boolean} 返回是否是数字
     */
    function isNumber(val) {
        var reg = /^[0-9]\d*$/;//正整数
        return reg.test(val);
    }

    function triggerRadio(name){
        let currentRadio;
        let sublingRadio;
        if(name == "channelIds"){
            currentRadio = $("#chose-channel-input")
            sublingRadio = currentRadio.next()
        } else if(name == "excludeChannelIds"){
            currentRadio = $("#chose-excludeChannelIds-input")
            sublingRadio = currentRadio.prev()
        }
        sublingRadio.css("display","none")
        currentRadio.css("display","block")
        form.render('radio');
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {

        // 监听“渠道”单选框
        form.on("radio(chose-channel)",function (data){
            console.log("触发单选框")
            triggerRadio(data.value)
        });


        // 监听保存按钮
        form.on('submit(zmn-form-submit)', function (data) {
            if (!data.field.categId) {
                layer.msg("请选择照片类型！", {"icon": 2});
                return false;
            }
            if (!isNumber(data.field.sort)) {
                layer.msg("请输入正整数！", {"icon": 2});
                return false;
            }

            let channelRadioVal = $("input[name=channel]:checked").val();
            if(channelRadioVal != "channelIds" && !data.field[channelRadioVal]){
                layer.msg("请选择排除渠道!", {"icon": 2});
                return false;
            }

            if (!data.field.bizType) {
                layer.msg("请选择应用业务类型！", {"icon": 2});
                return false;
            }
            if (!data.field.needReview) {
                layer.msg("请选择后台是否审核！", {"icon": 2});
                return false;
            }
            if (!data.field.autoAudit) {
                layer.msg("请选择自动审核！", {"icon": 2});
                return false;
            }
            if (!data.field.mustUpload) {
                layer.msg("请选择是否必传！", {"icon": 2});
                return false;
            }
            var url = CONF_BASE_URL + '/save.action';


            // 【应用渠道】 与 【过滤渠道】只能二选一，所以选中了某一个就要把另一个的值给置为空。
            let clearChannelName = channelRadioVal == "channelIds" ? "excludeChannelIds": "channelIds";
            data.field[clearChannelName] = ''

            $http.lockSave(url, data.field, data.elem).then(function (rsp) {
                layer.msg('操作成功', { icon: 1, time: 1000 }, function () {
                    parent.layer.closeAll();
                });
            }, (msg) => {
                layer.msg(msg);
            });
            return false
        });

    }

    /**
     * 描述: 图片上传方法
     * @param elemId
     * @param valueId
     */
    let indexUploadImags;

    function uploaderImage(elemId, valueId) {
        upload.render({
            elem: '#' + elemId
            , exts: 'jpg|png|jpeg'
            , acceptMime: 'image/*'
            , accept: 'images'
            , url: '/conf/attachment/orderPicture/uploader?timestamp=' + timestamp + '&elemId=' + elemId
            , size: 5120
            , beforeSend: function (obj) {
                indexUploadImags = layui.layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            }
            , done: function (res) {
                if (res.statusBool) {
                    let data = res.data;
                    $("#" + valueId).val(data);
                    $("#" + valueId+"s").attr("src",data).attr("style", "width: 0;height: 0");
                    reLoadImage(elemId, data);
                } else {
                    layer.msg(res.message)
                }
                layui.layer.close(indexUploadImags);
            }
        });
    }

    function reLoadImage(elemId, value, valueId) {
        zmnUploadUtil.reLoadImage($, elemId, value, valueId);
        let next = $("#" + elemId).next();
        let next1 = $(next).next();
        $(next).attr("style", "visibility:hidden !important");
        //$(next1).attr("style", "visibility:hidden !important");
    }

    /**
     * 初始化单选按钮
     */
    function initRadio(){
        let choseChannel = $("#chose-channel-radio");
        // 如果某个渠道存在值，就返回他的元素id名称
        let existsChannelName = dataVo.excludeChannelIds ? 'excludeChannelIds': 'channelIds';
        choseChannel.find("input[name=channel][value="+existsChannelName+"]").prop("checked",true)
        triggerRadio(existsChannelName)
    }

    /**
     * 初始化页面
     */
    function initPage() {
        // 初始化图片预览器
        previewer.initTextList('.container-images');

        uploaderImage("egImgSrc", "egSrc");
        // 点击删除图片
        $(document).on('click', '.btn-delete', function () {
            let $uploadDiv = $(this).parent().prev().prev();
            $uploadDiv.attr("style", "");
            $uploadDiv.find(".layui-upload-drag").attr("style", "");
            $uploadDiv.find("i").attr("style", "");
            $uploadDiv.find("p").attr("style", "");
            $uploadDiv.find(":hidden").val("");
            $uploadDiv.find("img").prop("src", "");
        });
        // 点击放大
        $(document).on('click', '.btn-review', function () {
            if (!$(this).parent().prev().prev().find("input").eq(0).val()) {
                layer.msg("请上传对应图片再预览");
                return;
            }
            let $container = $(this).parent().prev().prev().find("img").eq(0);
            $container.viewer().on('hide', function () {
                $container.viewer('destroy');
            });
            let index = $(this).index();
            $container.viewer('view', index);
        });

        reLoadImage('egImgSrc', dataVo.egSrc,'egSrc');
        $("#egSrc").val(dataVo.egSrc);
        $("#egImgSrcShow").attr("src",dataVo.egSrc).attr("style", "width: 0;height: 0");

    }

    /**
     *
     * 初始化下拉框
     */
    function initSelect(){
        zmnSelect.selectlServBizUnits({
            bizTypeSelectId: 'bizType',
            // bizLineSelectId: 'bizLineIds',
        }, {
            bizTypeSelectId: {
                selectedValues: dataVo.bizType
            },
            bizLineSelectId: {
                selectedValues:dataVo.bizLineIds === null ? null : dataVo.bizLineIds.split(","),
            }
        });

        zmnOmsSelect.selectConfOrderAttachmentCategory('categId', {
            isRadio:true,
            selectedValues: dataVo.categId === null ? null : dataVo.categId,
            tips: "全部",   //默认提示
            type: 1,
            page: {
                enable: true,
                remote:true,
                pageSize: 2000
            },
            remote: {
                events: {
                    extendParams: function () {
                        return {
                            status: 2
                        }
                    }
                }
            }
        });

        // 应用渠道
        zmnSelect.searchChannel('channelIds', {
            selectedValues:dataVo.channelIds === null ? null : dataVo.channelIds.split(","),
            remote: {
                events: {
                    extendParams: function () {
                        return {
                            "rank": 2, //渠道层级：Integer类型；1-查询一级渠道，2-查询二级渠道,null不限
                        }
                    }
                }
            },
            events: {
                changed: function (values) {
                }
            }
        });

        // 排除渠道
        zmnSelect.searchChannel('excludeChannelIds', {
            selectedValues:dataVo.excludeChannelIds === null ? null : dataVo.excludeChannelIds.split(","),
            remote: {
                events: {
                    extendParams: function () {
                        return {
                            "rank": 2, //渠道层级：Integer类型；1-查询一级渠道，2-查询二级渠道,null不限
                        }
                    }
                }
            },
            events: {
                changed: function (values) {
                }
            }
        });

        zmnSelect.selectServCategory('servCategIds', {
            selectedValues: dataVo.servCategIds === null ? null : dataVo.servCategIds.split(","),
        });
    }

    function init() {
        initEvent();
        initRadio();
        initPage();
        initSelect();
    }
    init();
    exports('oms_conf_attachment_orderPicture_detail');
});
